﻿using NHibernate;
using NHibernate.Cfg;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cyss.Core.Repository.NHibernate
{
    public class NHibernateContext
    {
        private static readonly ISessionFactory _sessionFactory;

        /// <summary>
        /// 
        /// </summary>
        public ISession Session { set; get; }

        static NHibernateContext()
        {
            var configuration = new Configuration();
            configuration.SetProperty("connection.provider", "NHibernate.Connection.DriverConnectionProvider");
            configuration.SetProperty("connection.driver_class", "NHibernate.Driver.SqlClientDriver");
            configuration.SetProperty("dialect", "NHibernate.Dialect.MsSql2005Dialect");
            configuration.SetProperty("proxyfactory.factory_class", "NHibernate.Bytecode.DefaultProxyFactoryFactory, NHibernate");
            configuration.SetProperty("format_sql", "true");
            configuration.SetProperty("show_sql", "true");
            configuration.SetProperty("connection.connection_string", IOCEngine.Resolve<IConnectionString>().Value);
            _sessionFactory=configuration.Configure().BuildSessionFactory();
        }

        public ISession GetCurrentSession()
        {
            if (Session==null)
            {
                Session= _sessionFactory.OpenSession();
            }
            return Session;
        }

        public void CloseSession()
        {
            if (Session!=null)
            {
                Session.Close();
            }
        }

        public void CloseSessionFactory()
        {
            if (_sessionFactory != null)
            {
                _sessionFactory.Close();
            }
        }

    }
}
